package com.springapp.mvc.controllers;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/")
public class MainController {

    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        putUsernameAndAuthoritiesIntoModel(model);

        return "welcome";
    }

    @RequestMapping(value = "/userinfo/")
    public String userInfo(ModelMap model, HttpServletRequest request) {
        putUsernameAndAuthoritiesIntoModel(model);

        model.put("Cookies", request.getCookies());

        return "userinfo";
    }

    private static void putUsernameAndAuthoritiesIntoModel(ModelMap model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        try {
            UserDetails principal = (UserDetails) auth.getPrincipal();
            model.put("username", principal.getUsername());
            model.put("authorities", principal.getAuthorities());
        } catch (Exception e) {
            model.put("username", "anonymous");
        }
    }

    @RequestMapping(value = "/admin/")
    public ModelAndView admin() {
        return new ModelAndView("admin");
    }

    @RequestMapping(value = "/supervisor/")
    public ModelAndView supervisor() {
        return new ModelAndView("supervisor");
    }

    @RequestMapping(value = "/login_page")
    public ModelAndView login() {
        return new ModelAndView("login_page");
    }

    @RequestMapping(value = "/logout_page")
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        return new ModelAndView("welcome");
    }

    @RequestMapping(value = "/feed/")
    public String feed(ModelMap model) {
        return "feed";
    }

    @RequestMapping(value = "/articles/")
    public String articles(ModelMap model) {
        return "articles";
    }


}

